import requests
import base64
import json
import urllib.parse

from Crypto.Cipher import AES
from flup.server.fcgi import WSGIServer

PAD_ZERO = 0
PAD_PKCS5 = 1
PAD_PKCS7 = 2


def decryptAesCbc(content, key, iv, padding):
    key_bytes = bytes(key, encoding="utf-8")
    iv_bytes = bytes(iv, encoding="utf-8")
    # 初始化解码器
    cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
    # base64解码
    content_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = cipher.decrypt(content_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding="utf-8")
    # 去补码
    if padding:
        result = pkcs7unpadding(result)

    return result


def delPadding(text):
    length = len(text)
    pad = ord(text[length - 1])
    return text[0:length - pad]


def pkcsPadding(data):
    length = len(data)
    pad = 16 - length % 16
    i = 0
    while(i < pad):
        data += chr(pad).encode("utf-8")
        i += 1

    return data


def zeroPadding(data):
    length = len(data)
    pad = 16 - length % 16
    i = 0
    while(i < pad):
        data += chr(0).encode("utf-8")
        i += 1

    return data


def decryptAesEcb(content, key, padding):
    key_bytes = bytes(key, encoding="utf-8")
    # 初始化解码器
    cipher = AES.new(key_bytes, AES.MODE_ECB)
    # base64解码
    content_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = cipher.decrypt(content_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding="utf-8")
    # 去补码
    if padding:
        result = delPadding(result)

    return result


def encryptAesEcb(content, key, padding):
    key_bytes = bytes(key, encoding="utf-8")
    content_bytes = bytes(content, encoding="utf-8")
    # 补码
    if padding == 0:
        content_bytes = zeroPadding(content_bytes)
    else:
        content_bytes = pkcsPadding(content_bytes)
    # 初始化加密器
    cipher = AES.new(key_bytes, AES.MODE_ECB)
    # 加密
    encrypt_bytes = cipher.encrypt(content_bytes)
    # Base64加密
    result = str(base64.b64encode(encrypt_bytes), encoding="utf-8")

    return result


# def resp(environ, start_response):
#     start_response("200 OK", [("Content-Type", "text/plain")])
#     return ["Hello Python!\n"]
# print(decryptAesEcb(resp.text, "1234567890123456", True))

# if __name__ == '__main__':
#     WSGIServer(resp, bindAddress=("127.0.0.1", 8008)).run()

print(urllib.parse.quote(
    encryptAesEcb("123", "1234567890123456", PAD_PKCS5)))
